//
//  HealthViewController.m
//  MeiShiDa
//
//  Created by zby on 15/6/30.
//  Copyright (c) 2015年 zby. All rights reserved.
//

#import "HealthViewController.h"
#import "AFNetworking.h"
#import <SVProgressHUD.h>
#import "FoodModel.h"
#import "FoodCollectionViewCell.h"
#import <MJRefresh.h>
#import "FoodDetailViewController.h"

#import "KindFoodViewController.h"


//#define kFood @"http://www.tudali.com:7177/App/CaiDan/getContentList"


@interface HealthViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,KindFoodDelegate>
@property(nonatomic,strong )NSMutableArray *dataSourceArray;

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,assign)NSInteger start;
@end

@implementation HealthViewController


-(NSMutableArray *)dataSourceArray{
    if (!_dataSourceArray) {
        self.dataSourceArray=[NSMutableArray array];
    }
    return _dataSourceArray;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden=YES;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:19],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.724 green:0.389 blue:1.000 alpha:1.000];
    self.titleStr=[@"人气菜品" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self createNetworking];
    
    
    self.navigationItem.title=@"人气菜品";
    self.navigationController.navigationBar.backgroundColor=[UIColor redColor];
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"Image"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backFirst)];
    
    
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"iconfont-caidanyuandian-1"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(kinds)];
    
    self.start=0;
    self.view.backgroundColor=[UIColor whiteColor];

    [self createView];
}




//返回到第一个界面
-(void)backFirst{
    self.tabBarController.tabBar.hidden=NO;
    
    self.tabBarController.selectedIndex=0;
}

 // 添加传统的下拉刷新
-(void)addFresh{
    
    //添加头尾控件
    _collectionView.header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downFresh:)];
    _collectionView.footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upFresh)];
}

-(void)downFresh:(MJRefreshHeader *)header{
    
    self.start=0;
    [self.dataSourceArray removeAllObjects];
    [self createNetworking];
}

-(void)upFresh{
    _start+=10;
    
    [self createNetworking];
}



//请求数据
-(void)createNetworking{
    NSString *urlStr =@"http://www.tudali.com:7177/App/CaiDan/getContentList";
    NSString *otherStr=[NSString stringWithFormat:@"CaiDanFenLei=%@&Start=0&Limit=10",_titleStr];
    
//    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    NSString *otherStr1=[otherStr stringByReplacingOccurrencesOfString:@"Start=0" withString:[NSString stringWithFormat:@"Start=%ld",(long)_start]];

    NSString *url=[NSString stringWithFormat:@"%@?%@",urlStr,otherStr1];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: url]];
    [SVProgressHUD show];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        //系统自带JSON解析
        NSArray *arr= [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        [SVProgressHUD dismiss];
        if ([arr count]==0) {
            //没有更多数据
            [_collectionView.footer noticeNoMoreData];
            return;
        }else{
            [_collectionView.footer resetNoMoreData];
        }
        
        for (NSDictionary *dic in arr) {
            FoodModel *model=[[FoodModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSourceArray addObject:model];
        }
        [_collectionView.header endRefreshing];
        [_collectionView.footer endRefreshing];
        [_collectionView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@", error);
        [SVProgressHUD dismiss];
        [_collectionView.header endRefreshing];
        [_collectionView.footer endRefreshing];

    }];
    [operation start];
}


//创建collectionView
-(void)createView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((SCREEN_WIDTH-30)/2, (SCREEN_WIDTH-30)/2);//给我们每个item的大小进行赋值
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(10, 0, SCREEN_WIDTH-20, SCREEN_HEIGHT) collectionViewLayout:layout];
    _collectionView.showsVerticalScrollIndicator=NO;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;//数据源协议
    _collectionView.delegate = self;//代理协议

    //注册一个UICollectionViewCell的类
    [_collectionView registerClass:[FoodCollectionViewCell class] forCellWithReuseIdentifier:@"abc"];
    
    [self.view addSubview:_collectionView];
    [self addFresh];

}

//collectionView  代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [_dataSourceArray count];
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    FoodCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"abc" forIndexPath:indexPath];
    if ([_dataSourceArray count]>1) {
        cell.model=_dataSourceArray[indexPath.row];

        
    }
    return cell;
}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    FoodDetailViewController *foodDetail=[[FoodDetailViewController alloc]init];

    if ([_dataSourceArray count]>1) {
        FoodModel *food=_dataSourceArray[indexPath.row];
        
        foodDetail.ID=food.ID;
    }
//    [self changeLayout];
    [self.navigationController pushViewController:foodDetail animated:YES];
}

//右上角button方法   分类筛选
-(void)kinds{
    KindFoodViewController *kindVC=[[KindFoodViewController alloc]init];
    kindVC.titleDelegate=self;
//    [self changeLayout];
    
    [self.navigationController pushViewController:kindVC animated:YES];
}


//kindVC的代理方法
-(void)kindFoodVC:(KindFoodViewController *)kindFoodVC navigationTitle:(NSString *)title{
    _start=0;
    self.navigationItem.title=title;
    self.titleStr=[title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self.dataSourceArray removeAllObjects];
    [self createNetworking];
}

//改变布局加动画
- (void)changeLayout{
    CATransition *animation=[CATransition animation];
    animation.type=@"rippleEffect";
    animation.subtype=kCATransitionFromBottom;
    animation.duration=1.5;
    [self.view.superview.layer addAnimation:animation forKey:@"donghua1"];
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
